package com.jie.creator.singleton.demo08;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @description:测试使用序列化反序列化破坏单例模式
 * 桌面路径 C:\Users\jie\Desktop
 * @author: jie
 * @time: 2022/1/29 18:51
 */
public class Test {
    public static void main(String[] args) throws Exception{
        //调用写入操作
        writeObject2File();
        //调用读取操作
        Singleton s1 = readObjectFromFile();
        Singleton s2 = readObjectFromFile();
        //判断地址是否相同
        System.out.println(s1==s2);
    }
    /**
     * @description:从文件读取数据（对象）
     * @author: jie
     * @time: 2022/1/29 19:04
     */
    public static Singleton readObjectFromFile()throws Exception{
        //1、创建对象输入流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:\\Users\\jie\\Desktop\\a.txt"));
        //2、读取对象
        Singleton singleton = (Singleton) ois.readObject();
        //释放资源
        ois.close();
        return singleton;
    }

    /**
     * @description:向文件中写数据（对象）
     * @author: jie
     * @time: 2022/1/29 18:55
     */
    public static void writeObject2File() throws Exception{
        //1、获取Singleton对象
        Singleton instance = Singleton.getInstance();
        //2、创建对象(输出流对象)
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("C:\\Users\\jie\\Desktop\\a.txt"));
        //3、写对象
        oos.writeObject(instance);
        //4、释放资源
        oos.close();
    }
}
